<template>
    <div class="app-container">
        <div class="search-container">
            <el-form :inline="true" :model="queryParams" label-width="105px">
              <el-form-item label="结账类型" prop="acctType">
                <el-select v-model="queryParams.acctType" placeholder="请选择结账类型" style="width: 150px">
                  <el-option
                      v-for="item in dicts.acctTypeDict"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
                <el-form-item label="结账起始时间" prop="beginTime">
                    <el-date-picker v-model="queryParams.beginTime"
                                    :disabled="beginTimeDisabled" placeholder="结账起始时间"
                                    type="datetime" value-format="YYYY-MM-DD HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结账截止时间" prop="endTime">
                    <el-date-picker v-model="queryParams.endTime" placeholder="结账截止时间"
                                    type="datetime" value-format="YYYY-MM-DD HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button class="ml10" type="success" @click="settleAccounts">
                        <svg-icon class="mr5" icon-class="acctSelect"/>
                        获取结账信息
                    </el-button>
                    <el-button type="primary" @click="refreshClick">
                        <template #icon>
                            <i-ep-search/>
                        </template>
                        刷新最新时间
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="search-container" style="padding: 18px 10px 10px 10px">
            <el-form ref="showParamsRef" :inline="true" :model="showForm" label-width="105px">
                <el-form-item label="结账人:" prop="operationUserName">
                    <el-input v-model="showForm.operationUserName" class="width-120" disabled
                              @keyup.enter="handleQuery"/>
                </el-form-item>
                <el-form-item label="结账时间" prop="checkYearMonth">
                    <el-date-picker v-model="showForm.endTime" clearable disabled
                                    placeholder="结账时间" type="datetime">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div style="display: flex">
                <div class="card-div-child" style="border: 1px solid #1ab394;background-color: rgba(26,179,148,0.08)">
                    <div class="card-wrap-class-content">
                        <img alt="" src="@/assets/images/acctInfo/number_of_sheets.png"/>
                        <div style="flex: 1;color: #1ab394">
                            <div class="mt20 div-font-size ">收费张数</div>
                            <h2 class="text-blue div-font-size ">
                                {{ numberOfSheets }}张
                            </h2>
                        </div>
                    </div>
                </div>
                <div class="card-div-child" style="border: 1px solid #f68290;background-color: rgba(246,130,144,0.08)">
                    <div class="card-wrap-class-content">
                        <img alt="" src="@/assets/images/acctInfo/ret_number_of_sheets.png"/>
                        <div style="flex: 1;color: #f68290">
                            <div class="mt20 div-font-size ">退费张数</div>
                            <h2 class="text-blue div-font-size ">
                                {{ retNumberOfSheets }}张
                            </h2>
                        </div>
                    </div>
                </div>
                <div class="card-div-child" style="border: 1px solid #f58123;background-color: rgba(245,129,35,0.08)">
                    <div class="card-wrap-class-content">
                        <img alt="" src="@/assets/images/acctInfo/refund_amount.png"/>
                        <div style="flex: 1;color: #f58123">
                            <div class="mt20 div-font-size ">退费金额</div>
                            <h2 class="text-blue div-font-size ">
                                {{ refundAmount }}元
                            </h2>
                        </div>
                    </div>
                </div>
                <div class="card-div-child" style="border: 1px solid #ecc625; background-color: rgba(249,236,25,0.08)">
                    <div class="card-wrap-class-content">
                        <img alt="" src="@/assets/images/acctInfo/fee_amount.png"/>
                        <div style="flex: 1;color: #ecc625">
                            <div class="mt20 div-font-size ">总金额</div>
                            <h2 class="text-blue div-font-size ">
                                {{ feeAmount }}元
                            </h2>
                        </div>
                    </div>
                </div>
                <div class="card-div-child" style="border: 1px solid #2e47f6;background-color: rgba(46,71,246,0.08)">
                    <div class="card-wrap-class-content">
                        <img alt="" src="@/assets/images/acctInfo/fee_amount2.png"/>
                        <div style="flex: 1;color: #2e47f6">
                            <div class="mt20 div-font-size ">实收总额</div>
                            <h2 class="text-blue div-font-size ">
                                {{ feeAmount2 }}元
                            </h2>
                        </div>
                    </div>
                </div>
                <div class="card-div-child" style="border: 1px solid #2ff110;background-color: rgba(47,241,16,0.08)">
                    <div class="card-wrap-class-content">
                        <img alt="" src="@/assets/images/acctInfo/total_revenue.png"/>
                        <div style="flex: 1;color: #2ff110">
                            <div class="mt20 div-font-size ">营收总额</div>
                            <h2 class="text-blue div-font-size ">
                                {{ feeAmount2 }}元
                            </h2>
                        </div>
                    </div>
                </div>
            </div>
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-table v-adaptive="470" :border="true" :data="moneyToMoneyTypeList"
                              :header-cell-style="$headerCellStyle" :stripe="true" :summary-method="getSummaries"
                              highlight-current-row
                              show-summary>
                        <el-table-column align="center" label="支付方式" min-width="150" prop="moneyTypeName"/>
                        <el-table-column align="center" label="收费">
                            <el-table-column align="center" label="收款" min-width="120" prop="paymentAmount">
                                <template #default="scope">
                                    <span class="ys-css">{{ parseFloat(scope.row.paymentAmount).toFixed(2) }} 元</span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="退款" min-width="120" prop="refundAmount">
                                <template #default="scope">
                                    <span
                                        class="ret-ys-css">{{
                                            parseFloat(scope.row.refundAmount).toFixed(2)
                                        }} 元</span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="合计实收" min-width="120" prop="totalReceived">
                                <template #default="scope">
                                    <span class="ys-css">{{ parseFloat(scope.row.totalReceived).toFixed(2) }} 元</span>
                                </template>
                            </el-table-column>

                        </el-table-column>
                    </el-table>
                </el-col>
                <el-col :span="12">
                    <el-table v-adaptive="470" :border="true" :data="groupByInClassOnInpList"
                              :header-cell-style="$headerCellStyle"
                              :stripe="true" :summary-method="getSummaries" highlight-current-row
                              show-summary>
                        <el-table-column align="center" label="收据分类明细" min-width="150" prop="classOnInpName"/>
                        <el-table-column label="收费" min-width="150" prop="charges">
                            <template #default="scope">
                                <span class="ys-css">{{ parseFloat(scope.row.charges).toFixed(2) }} 元</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
        </div>
        <div class="search-container" style="padding: 18px 10px 10px 10px">
            <el-form :inline="true" :model="submitForm" label-width="105px">
                <el-form-item label="合计金额：">
                    <span class="ys-css">{{ feeAmount2 }}元</span>
                </el-form-item>
                <el-form-item label="结账人：">
                    {{ showForm.operationUserName }}
                </el-form-item>
                <el-form-item label="结账时间：">
                    {{ showForm.endTime }}
                </el-form-item>
                <el-form-item style="float: right">
                    <el-button class="ml10" type="success" @click="confirmTheAccountFun">
                        <svg-icon class="mr5" icon-class="acctSelect"/>
                        确认结账
                    </el-button>
                </el-form-item>
            </el-form>

        </div>
    </div>
</template>

<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user";
import {getUserCostAndTotal} from "@/api/inpFees/inpFeesMaster.ts"
import {confirmTheAccount, getLastAcctEndDate} from "@/api/inpAcct/inpAcctMaster.ts"
import {ElRow} from "element-plus";
import {getPatPrepayCostAndTotal} from "@/api/hospitalization/patPrepayment.ts";

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const {proxy} = getCurrentInstance() as any;
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const queryParams = ref({
    acctType: "4",
    beginTime: date + "00:00:00",
    endTime: proxy.$parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")
})
const dateRange = ref<any>([])
const showForm = ref<any>({
    operationUser: userInfo.userId,
    operationUserName: userInfo.nickName,
})
// 结账开始时间是否禁用
const beginTimeDisabled = ref<boolean>(true);
const whetherToClick = ref<boolean>(false)
// 合计金额
// const totalAmount = ref<number>(0.00)
const submitForm = ref<any>({})
// 结账支付方式列表list
const moneyToMoneyTypeList = ref<any>([])
// 结账住院收据分类列表list
const groupByInClassOnInpList = ref<any>([])
//营收总额
const totalRevenue = ref<number>(0)
//总金额
const feeAmount = ref<number>(0)
//实收总额
const feeAmount2 = ref<number>(0)
//收费张数
const numberOfSheets = ref<number>(0)
//退费金额
const refundAmount = ref<number>(0)
//退费张数
const retNumberOfSheets = ref<number>(0)

const dicts = {
  acctTypeDict: [
    { label: '住院结算结账', value: '4' },
    { label: '预交金结账', value: '5' }
  ],
};
const getLabel = (dict, value) => {
  const found = dict.find(item => item.value === value);
  return found ? found.label : value;
};
/**
 * 结账按钮点击事件
 */
function settleAccounts() {
    showForm.value.endTime = queryParams.value.endTime;
    dateRange.value = [queryParams.value.beginTime, queryParams.value.endTime];
    getUserCostAndTotalFun()
    whetherToClick.value = true
}

watch(
    () => queryParams.value.acctType,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        getLastAcctEndDateFun(); // 调用获取最新结账结束时间的方法
      }
    }
);
/**
 * 刷新
 */
function refreshClick() {
    queryParams.value.endTime = proxy.$parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")
    settleAccounts()
    whetherToClick.value = true
}

/**
 * 结账时间
 */
function acctTimeChange() {

}

function handleQuery() {
}

/**
 * 确认结账
 */
function confirmTheAccountFun() {
    if (!whetherToClick.value || moneyToMoneyTypeList.value.length <= 0) {
        return ElMessage.error("请点击【结账】按钮，获取到收费数据后，再进行【确认结账】")
    }
    ElMessageBox.confirm("确认要进行【确认结账】操作吗", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        const query = {
            acctType: queryParams.value.acctType,
            isMerge: "N",
            orgId: userInfo.orgId,
            acctUserName: userInfo.nickName,
            operationUser: showForm.value.operationUser,
            createBy: showForm.value.operationUser,
        }
        confirmTheAccount(proxy.$addDateRange(query, dateRange.value)).then(() => {
            ElMessage.success("结账成功")
            moneyToMoneyTypeList.value = []
            // 结账住院收据分类列表list
            groupByInClassOnInpList.value = []
            //营收总额
            totalRevenue.value = 0
            //总金额
            feeAmount.value = 0
            //实收总额
            feeAmount2.value = 0
            //收费张数
            numberOfSheets.value = 0
            //退费金额
            refundAmount.value = 0
            //退费张数
            retNumberOfSheets.value = 0
            getLastAcctEndDateFun()
        })
    }).catch(() => {
        ElMessage.info("取消操作");
    });

}

function getUserCostAndTotalFun() {
    const query = {
        orgId: userInfo.orgId,
        operationUser: showForm.value.operationUser,
        createBy: showForm.value.operationUser,
    }
  let apiCall;

  if (queryParams.value.acctType == "4") { // 住院结算结账
    apiCall = getUserCostAndTotal(proxy.$addDateRange(query, dateRange.value));
  } else if (queryParams.value.acctType == "5") { // 预交金结账
    apiCall = getPatPrepayCostAndTotal(proxy.$addDateRange(query, dateRange.value));
  } else {
    ElMessage.error("暂不支持其他结账类型");
    return;
  }
  apiCall.then((res) => {
    if (res.data.error) {
      numberOfSheets.value = 0
      retNumberOfSheets.value = 0
      feeAmount.value = 0
      feeAmount2.value = 0
      totalRevenue.value = 0
      refundAmount.value = 0
      moneyToMoneyTypeList.value = []
      groupByInClassOnInpList.value = []
      ElMessage.error(res.data.errorMsg)
    } else {
      const costAndTotalVo = res.data.costAndTotalVo
      numberOfSheets.value = costAndTotalVo.numberOfSheets
      retNumberOfSheets.value = costAndTotalVo.retNumberOfSheets
      feeAmount.value = Number(Number(costAndTotalVo.feeAmount).toFixed(2))
      feeAmount2.value = Number(Number(costAndTotalVo.feeAmount2).toFixed(2))
      totalRevenue.value = Number(Number(costAndTotalVo.feeAmount2).toFixed(2))
      refundAmount.value = Number(Number(costAndTotalVo.refundAmount).toFixed(2))
      moneyToMoneyTypeList.value = res.data.moneyToMoneyTypeList
      groupByInClassOnInpList.value = res.data.groupByInClassOnInpList
    }
  });
}

const getSummaries = (param: any) => {
    const {columns, data} = param
    const sums: (string | VNode)[] = []
    columns.forEach((column, index) => {
        if (index === 0) {
            // sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
            sums[index] = h('div', {style: {}}, [
                '合计：',
            ])
            return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => Number.isNaN(value))) {
            sums[index] = `￥ ${values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                    return (Number(prev) + Number(curr)).toFixed(2)
                } else {
                    return (Number(prev)).toFixed(2)
                }
            }, 0)} 元`
        } else {
            sums[index] = 'N/A'
        }
    })

    return sums
}

function getLastAcctEndDateFun() {
    const query = {
        acctType: queryParams.value.acctType,
        acctUserId: userInfo.userId,
        orgId: userInfo.orgId
    }
    getLastAcctEndDate(query).then((res: resType) => {
        if (res.data.acctEndTime) {
            beginTimeDisabled.value = true
            queryParams.value.beginTime = res.data.acctEndTime
        } else {
            beginTimeDisabled.value = false
            queryParams.value.beginTime = proxy.$parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")
        }
    })
}

getLastAcctEndDateFun()
</script>
<style scoped>
.card-div-child {
    height: 70px;
    -webkit-box-align: center;
    align-items: center;
    margin: 0 5px 5px 5px;
    width: 200px;
    border-radius: 10px;
}

.card-wrap-class-content {
    display: flex;
    height: 100%;
    justify-content: center;
    align-items: center;

    > img {
        height: 50px;
        margin-right: 20px;
        margin-left: 10px;
        flex: 0.2
    }

    div {
        width: 90px;
    }
}

.div-font-size {
    font-size: 17px;
}
</style>
